<template>
  <div>
    <!-- 面包屑导航 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/welcome' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>
    <!-- 卡片区域 -->
    <el-card class="box-card">
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input
            placeholder="请输入内容"
            v-model="queryInfo.query"
            clearable
            @clear="getUserList"
          >
            <el-button
              slot="append"
              icon="el-icon-search"
              @click="getUserList"
            ></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true"
            >用户添加</el-button
          >
        </el-col>
      </el-row>
      <!-- 表格区域 -->
      <el-table :data="userList.users" border style="width: 100%" stripe>
        <el-table-column label="#" type="index"></el-table-column>
        <el-table-column
          prop="username"
          label="姓名"
          width="180"
        ></el-table-column>
        <el-table-column
          prop="email"
          label="邮件"
          width="180"
        ></el-table-column>
        <el-table-column prop="mobile" label="电话"> </el-table-column>
        <el-table-column prop="role_name" label="角色"> </el-table-column>
        <el-table-column label="状态">
          <!-- 作用域插槽 -->
          <template slot-scope="scope">
            <el-switch
              v-model="scope.row.mg_state"
              @change="userStateChange(scope.row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="操作" width="180">
          <template slot-scope="scope">
            <el-button
              type="primary"
              icon="el-icon-edit"
              size="mini"
              @click="editUser(scope.row.id)"
            ></el-button>
            <el-button
              type="danger"
              icon="el-icon-delete"
              size="mini"
              @click="deleteUser(scope.row.id)"
            ></el-button>
            <el-tooltip
              class="item"
              effect="dark"
              content="分配角色"
              placement="top"
              :enterable="false"
            >
              <el-button
                type="warning"
                icon="el-icon-setting"
                size="mini"
                @click="setRoles(scope.row)"
              ></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[5, 8, 10, 15]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 用户添加弹出区域 -->
    <el-dialog
      title="添加用户"
      :visible.sync="dialogVisible"
      width="50%"
      @close="addDialogClose"
    >
      <!-- 表单区域 -->
      <el-form
        ref="RulesRef"
        :model="ruleForm"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="ruleForm.username"></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input v-model="ruleForm.password"></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="ruleForm.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="ruleForm.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="adduser">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改对话框区域 -->
    <el-dialog
      title="修改用户"
      :visible.sync="editDialogVisible"
      width="50%"
      @close="editDialogClose"
    >
      <el-form
        ref="editRef"
        :model="UserInfo"
        :rules="rules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="UserInfo.username" disabled></el-input>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="UserInfo.email"></el-input>
        </el-form-item>
        <el-form-item label="手机" prop="mobile">
          <el-input v-model="UserInfo.mobile"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUserInfoSubmit">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色对话框 -->
    <el-dialog
      title="分配角色"
      :visible.sync="setRolesdialogVisible"
      width="50%"
      @close="setRolesClose"
    >
      <div>
        <p>当前用户：{{ userInfoRow.username }}</p>
        <p>当前角色：{{ userInfoRow.role_name }}</p>
        <p>分配新角色：
          <el-select v-model="selectRoles" placeholder="请选择">
            <el-option
              v-for="item in rolesList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id"
            >
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="setRolesdialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveRolesInfo"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "User",

  data() {
    //验证邮箱的规则
    var checkEmail = (rule, value, callback) => {
      const regEmail =
        /^[_a-z0-9-]+(\.[_a-z0-9-]+)*@[a-z0-9-]+(\.[a-z0-9-]+)*(\.[a-z]{2,})$/;
      if (regEmail.test(value)) {
        return callback();
      } else {
        callback(new Error("请输入合法的邮箱"));
      }
    };
    //验证手机号规则
    var checkiPhone = (rule, value, callback) => {
      const regiPhone =
        /^(13[0-9]|14[01456879]|15[0-35-9]|16[2567]|17[0-8]|18[0-9]|19[0-35-9])\d{8}$/;
      if (regiPhone.test(value)) {
        return callback();
      } else {
        callback(new Error("请输入合法的手机号"));
      }
    };

    //验证手机号的规则
    return {
      queryInfo: {
        query: "",
        pagenum: 1,
        pagesize: 5,
      },
      userList: {}, //存请求数据的data对象
      total: 0,
      dialogVisible: false, //是否显示添加用户对话框
      editDialogVisible: false, //是否显示修改用户对话框
      UserInfo: {}, //通过ID查询到用户的信息
      editUserInfo: {}, //修改后用户的信息
      setRolesdialogVisible: false, //分配角色是否隐藏于显示
      userInfoRow: {}, //每一行用户信息
      rolesList:[],//所有角色信息
      selectRoles:'',//选择的角色
      //   绑定输入的数据
      ruleForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },

      editUserForm: {
        username: "",
        password: "",
        email: "",
        mobile: "",
      },

      //表单验证
      rules: {
        username: [
          { required: true, message: "请输入用户名", trigger: "blur" },
          {
            min: 3,
            max: 10,

            message: "长度在 3 到 10 个字符",
            trigger: "blur",
          },
        ],
        password: [
          { required: true, message: "请输入密码", trigger: "blur" },
          {
            min: 6,
            max: 15,
            message: "长度在 6 到 15 个字符",
            trigger: "blur",
          },
        ],
        email: [
          { required: true, message: "请输入邮箱", trigger: "blur" },
          { validator: checkEmail, trigger: "blur" },
        ],
        mobile: [
          { required: true, message: "请输入手机号", trigger: "blur" },
          { validator: checkiPhone, trigger: "blur" },
        ],
      },
    };
  },

  created() {
    this.getUserList();
  },

  methods: {
    //获取菜单列表
    async getUserList() {
      const { data: res } = await this.$http.get("users", {
        params: this.queryInfo,
      });
      if (res.meta.status == 200) {
        this.userList = res.data;
        this.total = res.data.total;
        this.$message.success("获取菜单列表成功");
        console.log(res);
      } else {
        this.$message.error("获取菜单列表失败");
      }
    },

    //更新用户状态
    async userStateChange(userState) {
      const { data: res } = await this.$http.put(
        `users/${userState.id}/state/${userState.mg_state}`
      );
      console.log(res);
      if (res.meta.status == 200) {
        this.$message.success("更新用户状态成功");
      } else {
        this.$message.error("更新用户状态失败");
        userState.mg_state = !userState.mg_state;
      }
    },

    handleSizeChange(val) {
      //   console.log(`每页 ${val} 条`);
      this.queryInfo.pagesize = val;
      this.getUserList();
    },
    handleCurrentChange(val) {
      //   console.log(`当前页: ${val}`);
      this.queryInfo.pagenum = val;
      this.getUserList();
    },

    //监听添加对话框关闭事件
    addDialogClose() {
      this.$refs.RulesRef.resetFields();
    },
    //填写完信息后预校验
    adduser() {
      this.$refs.RulesRef.validate(async (valid) => {
        if (!valid) {
          return;
        } else {
          const { data: res } = await this.$http.post("users", this.ruleForm);
          // console.log(res)
          if (res.meta.status == 201) {
            this.$message.success("添加用户成功");
            this.dialogVisible = false;
            this.getUserList(); //重新获取列表
          } else {
            this.$message.error("添加用户失败");
          }
        }
      });
    },
    //通过iD查询用户信息
    async editUser(id) {
      const { data: res } = await this.$http.get("users/" + id);
      // console.log(res)
      if (res.meta.status == 200) {
        this.UserInfo = res.data;
        this.editDialogVisible = true;
        this.$message.success("查询用户信息成功");
      } else {
        this.$message.error("查询用户失败");
      }
    },
    // 修改窗口关闭后执行事件
    editDialogClose() {
      this.$refs.editRef.resetFields(); //重置表单的数据
    },
    //表单填写完后进行预校验
    editUserInfoSubmit() {
      this.$refs.editRef.validate(async (valid) => {
        if (valid) {
          const { data: res } = await this.$http.put(
            "users/" + this.UserInfo.id,
            {
              email: this.UserInfo.email,
              mobile: this.UserInfo.mobile,
            }
          );
          if (res.meta.status == 200) {
            this.editUserInfo = res.data;
            this.$message.success("修改用户信息成功");
            this.editDialogVisible = false; //编辑用户信息窗口关闭
            this.getUserList(); //重新更新菜单用户
          } else {
            this.$message.error("修改用户信息失败");
          }
        } else {
          return;
        }
      });
    },
    //删除用户
    async deleteUser(id) {
      const val = await this.$confirm(
        "此操作将永久删除该用户, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((error) => error);
      if (val == "confirm") {
        const { data: res } = await this.$http.delete("users/" + id);
        if (res.meta.status == 200) {
          this.$message.success("删除用户成功");
          this.getUserList();
        } else {
          this.$message.error("删除用户失败");
        }
      } else {
        this.$message.info("已取消删除");
      }
    },

    //分配用户角色
   async setRoles(userInfo) {
      this.userInfoRow = userInfo; //每行用户信息
       //获取角色信息
      const{data:res} =await this.$http.get('roles')
      if(res.meta.status==200){
        this.rolesList=res.data
        console.log(res)
      }
      this.setRolesdialogVisible = true; //显示对话框
    },

    //点击确认，分配角色
    async saveRolesInfo(){
      if(!this.selectRoles){
        this.$message.error('请选择要分配的角色')
      }else{
       const{data:res} =await this.$http.put(`users/${this.userInfoRow.id}/role`,{
          rid:this.selectRoles
        })
        if(res.meta.status==200){
          this.$message.success('分配角色成功')
          this.getUserList()
          this.setRolesdialogVisible=false
        }else{
          this.$message.error('分配角色失败')
        }
        
      }
    },

    //监听分配角色对话框关闭
    setRolesClose(){
      this.selectRoles=''//重置下拉框
      this.userInfoRow={}//重置用户信息
    }
    
  },
};
</script>

<style>
</style>